<?PHP
namespace App\Http\Controllers;

use App\Service\TaskService;
use App\Service\UserService;
use Illuminate\Http\Request;
use App\Models\Task;
use App\Models\TaskDaily;
use App\Models\User;
use Illuminate\Support\Facades\Validator;

class TaskController extends Controller {

    protected $task;
    protected $userService;

    function __construct(TaskService $task, UserService $user) {
        $this->task = $task;
        $this->userService = $user;
    }

    public function add(Request $request) {
        $input = $request->all();
        $this->validate($request, [
            'amount'       => 'required|int',
            'desc'         => 'required',
            'repeat_times' => 'required|int',
            'start_time'   => 'required|date',
        ]);

        if ($input['amount'] <= 0) {
            return self::responseError(1007, '无效的奖励金额');
        }

        if ($input['repeat_times'] < 1) {
            return self::responseError(1007, '任务至少重复一次');
        }
        $input['start_time'] = strtotime($input['start_time']);
        $id = $this->task->add($input);

        if (!$id) {
            return self::responseError(1004, '操作失败');
        }

        return self::responseSuccess(['id' => $id]);
    }

    public function taskList(Request $request) {
        $data = $this->task->getList($request->all());

        return self::responseSuccess($data);
    }

    public function taskInfo(Request $request) {
        $this->validate($request, [
            'task_id' => 'required|int',
        ]);
        $taskID = $request->get('task_id');
        $task = [];
        try {
            //task基本信息
            $task = Task::whereId($taskID)->with('createUser')->first();

            if (empty($task)) {
                return [];
            }

            $task = $task->toArray();
            $task['supervisors'] = explode(',', $task['supervisors']);
            $task['start_time'] = date('Y-m-d H:i:s', $task['start_time']);
            $task['end_time'] = date('Y-m-d H:i:s', $task['end_time']);

            //task完成情况
            $dailyData = [];
            $dailyTasks = TaskDaily::where('task_id', $taskID)->orderBy('id', 'desc')->get();

            if ($dailyTasks) {
                $dailyTasks = $dailyTasks->toArray();
                $dailyData = array_map(function($tmp){
                    return [
                        'id' => $tmp['id'],
                        'date' => $tmp['updated_at'],
                        'is_completed' => $tmp['state'],
                        'img' => $tmp['img'],
                        'content' => $tmp['content'],
                    ];
                }, $dailyTasks);
            }

            $user = UserService::authUser();

            $retData = [
                'is_mine'       => $task['uid'] == $user->id ? 1 : 0,
                'im_supervisor' => in_array($user->id, $task['supervisors']) ? 1 : 0,
                'task'          => $task,
                'daily'         => $dailyData,
            ];

            return self::responseSuccess($retData);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function supervisorsOfTask(Request $request) {
        try {
            $this->validate($request, [
                'task_id' => 'required|int',
            ]);
            $taskID = $request->get('task_id');
            $supervisorIDs = explode(',', Task::find($taskID)->supervisors);
            $supervisorArr = User::whereIn('id', $supervisorIDs)->get();
            if ($supervisorArr->count()) {
                $data = $supervisorArr->toArray();
            } else {
                $data = [];
            }
            return self::responseSuccess($data);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }

    public function taskListOfSupervisor(Request $request) {
        try {
            //app('db')->connection()->enableQueryLog();
            $this->validate($request, [
                'type' => 'required|int', //0:全部  1:已完成  2:未完成
            ]);
            $user = $this->userService->authUser();
            $uid = $user->id;
            $type = $request->get('type');
            $list = Task::whereRaw("find_in_set({$uid}, `supervisors`)")->with('createUser');
            $type && $list->where('state', $type);
            $list = $list->get();
            $list->each(function(Task &$task){
                $task->join_users = $task->task_join_users;
            });
            //$log = app('db')->getQueryLog();
            //dd($log);
            if ($list->count()) {
                $data = $list->toArray();
            } else {
                $data = [];
            }
            return self::responseSuccess($data);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}
